<?php
/**
 * 发货通知单
 * Created by PhpStorm.
 * User: echa
 * Date: 2018/1/30
 * Time: 21:15
 *
 */

namespace App\Services\Warehouse;

use App\Repositories\Warehouse\WarehouseRepository;
use PHPUnit\Runner\Exception;

class ConsignmentNoteService extends PublicService
{

    //发货通知表单ID
    //protected $Formid = 'SAL_DELIVERYNOTICE';


    protected $WarehouseRepository;
    protected $DirectTransfersService;
    protected $WarehouseService;
    protected $MisDeliveryService;
    public function __construct(WarehouseRepository $warehouseRepository,DirectTransfersService $directTransfersService,WarehouseService $warehouseService,MisDeliveryService $misDeliveryService)
    {
        parent::__construct(Config('k3cloud.ConsignmentNote'));
        $this->WarehouseRepository=$warehouseRepository;
        $this->DirectTransfersService=$directTransfersService;
        $this->WarehouseService=$warehouseService;
        $this->MisDeliveryService=$misDeliveryService;
    }

    /**
     * 保存
     * 1.formid：业务对象表单Id（必录）
     * 2.data：Json格式数据（详情参考Json格式数据）（必录）
     * 2.1.Creator：创建者名字（非必录）
     * 2.2.NeedUpDateFields：需要保存的字段,格式["fieldkey1","fieldkey2","entitykey1",...]，数组类型(非必录)
     * 2.3.NeedReturnFields：需要返回的结果字段,格式["fieldkey","entitykey.fieldkey",...]（非必录）
     * 2.4.IsDeleteEntry：是否删除分录，默认True删除（非必录）
     * 2.5.SubSystemId：菜单所在子系统Id（非必录）
     * 2.6.IsVerifyBaseDataField：是否验证所有的基础资料，默认False不验证（非必录）
     * 2.7.IsEntryBatchFill：是否批量填充分录：默认为Ture（非必录）
     * 2.8.Model：表单实体数据（必录）
     */
    public function SaveConsignmentNote($arrdata = [])
    {
            $goods=$this->PostGoodsData($arrdata['GoodsData']);
            if(!$goods){
                return false;
            }
            if(empty($arrdata['FID'])){
                $arrdata['FID']=0;
            }
            if(empty($arrdata['FBillNo'])){
                $arrdata['FBillNo']="";
            }
            if(empty($arrdata['discountamount'])){
                $arrdata['discountamount']=0;
            }
            if(empty($arrdata['freight'])){
                $arrdata['freight']=0;
            }
            $data = [
                        "FID" =>$arrdata['FID'],
                        "FBillTypeID" =>[
                            "FNumber" => "FHTZD01_SYS",
                        ],
                        "FBillNo" => $arrdata['FBillNo'],
                        "FDate" => date('Y-m-d H:i:s',time()),
                        "FDiscountAmount"=>$arrdata['discountamount'],
                        "FFreight"=>$arrdata['freight'],
                        "FSaleOrgId" => [
                            "FNumber" => config('k3cloud.organization'),
                        ],
                        "FSaleDeptID" =>[
                            "FNumber" => "",
                        ],
                        "FCustomerID" =>[
                            "FNumber" => config('k3cloud.appcustomer'),
                        ],
                        "FHeadDeliveryWay" =>[
                            "FNumber" => "",
                        ],
                        "FHeadLocId" => [
                            "FNUMBER" => ""
                        ],
                        "FCorrespondOrgId" => [
                            "FNumber" => "",
                        ],
                        "FCarrierID" => [
                            "FNumber" => "",
                        ],
                        "FCarriageNO" => $arrdata['order_sn'],//运输单号(订单号)
                        "FNote" => "",
                        "FDeliveryOrgID" => [
                            "FNumber" => config('k3cloud.organization'),
                        ],
                        "FDeliveryDeptID" => [
                            "FNumber" => ""
                        ],
                        "FStockerGroupID" =>[
                            "FNumber" => ""
                        ],
                        "FStockerID" => [
                            "FNumber" => ""
                        ],
                        "FSaleGroupID" => [
                            "FNumber" => ""
                        ],
                        "FSalesManID" => [
                            "FNumber" => ""
                        ],

                        "FReceiverContactID" => [
                            "FName" => ""
                        ],
                        "FReceiveAddress" => "",
                        "FSettleID" => [
                            "FNumber" => config('k3cloud.appcustomer')
                        ],
                        "FPayerID" =>[
                            "FNumber" => config('k3cloud.appcustomer')
                        ],
                        "FRECEIPTCONDITIONID" => [
                            "FNumber" => ""
                        ],
                        "FOwnerTypeIdHead" => "BD_OwnerOrg",
                        "FOwnerIdHead" => [
                            "FNumber" => ""
                        ],
                        "SubHeadEntity" => [
                            "FSettleOrgID" => [
                                "FNumber" => config('k3cloud.organization')
                            ],
                            "FSettleCurrID" => [
                                "FNumber" => "PRE001"
                            ],
                            "FSettleTypeID" => [
                                "FNumber" => ""
                            ],
                            "FLocalCurrID" => [
                                "FNumber" => "PRE001"
                            ],
                            "FExchangeTypeID" => [
                                "FNumber" => "HLTX01_SYS"
                            ],
                            "FExchangeRate" => 1.0,
                            "FCreChkDays" => 0,
                            "FCreChkAmount" => 0.0,
                        ],
                        "FEntity" =>$goods
                ];
                return  $this->save($data);
    }


    /**
    批量保存
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.NumberSearch：是否使用Number来搜索基础资料，默认为True（非必录）
    2.2.ValidateFlag：是否验证标志，布尔类型,默认为True（非必录）
    2.3.IsDeleteEntry：是否删除分录，默认True删除（非必录）
    2.4.NeedUpDateFields：需要保存的字段,格式["fieldkey1","fieldkey2","entitykey1",...]，数组类型(非必录)
    2.5.NeedReturnFields：需要返回的结果字段,格式["fieldkey","entitykey.fieldkey",...]（非必录）
    2.6.SubSystemId：菜单所在子系统Id（非必录）
    2.7.Model：表单实体数据（必录）
    2.8.BatchCount：批量保存线程数，整形（非必录）

     */
    public function BatchSaveConsignmentNote($arrdata=[]){
        $data=$this->PostSaveData($arrdata);
        if(!$data){
            return false;
        }
        return $this->batchsave($data);

    }


    /**
    提交
     *
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */

    public function  SubmitConsignmentNote($Numbers=[]){
        return $this->submit($Numbers);
    }

    /**
    审核
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */
    public function AuditConsignmentNote($Numbers=[]){
        return $this->audit($Numbers);
    }

    /**
       反审核
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
        2.1.CreateOrgId：创建者组织，字符串类型（非必录）
        2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */
    public function unAuditConsignmentNote($Numbers=[]){
        return $this->unAudit($Numbers);
    }

    /**
     *单据列表查询
     * 1.data：Json格式数据（详情参考Json格式数据）（必录）
    1.1.FormId：业务对象表单Id（必录）
    1.2.FieldKeys：字段keys，字符串类型用逗号分隔，比如"key1,key2..."（必录）
    1.3.FilterString：过滤（非必录）  FNumber=''
    1.4.OrderString：排序字段（非必录）
    1.5.TopRowCount：总行数（非必录）
    1.6.StartRow：开始行（非必录）
    1.7.Limit：最大行数，不能超过2000（非必录）
     */
    public function ExecuteBillQueryConsignmentNote($FieldKeys='',$FilterString='',$OrderString='',$TopRowCount=0,$StartRow=0,$Limit=20)
    {
        if (empty($FieldKeys)) {
            $FieldKeys='FBillNo,FDocumentStatus,FCreateDate,FDate,FCarriageNO,FCLOSESTATUS,FCancelStatus';
        }
        return $this->ExecuteBillQuery($FieldKeys,$FilterString,$OrderString,$TopRowCount,$StartRow,$Limit);

    }

    /**
    *   订单商品数据列表
     *
     */
    private function PostGoodsData($GoodsData){
        if(!is_array($GoodsData)){
            return false;
        }
        $goods=array();
        $FOwnerTypeBDSupplier=config('k3cloud.FOwnerTypeBDSupplier');
        $FOwnerTypeBDOwnerOrg=config('k3cloud.FOwnerTypeBDOwnerOrg');
        foreach ($GoodsData as $k=>$v){
            $FOwnerFNumber=config('k3cloud.organization');
            if($v['k3_vmi']){
                $FOwnerTypeID=$FOwnerTypeBDSupplier;
                $FOwnerFNumber=$v['k3_supplier_sn'];
            }else{
                $FOwnerTypeID=$FOwnerTypeBDOwnerOrg;
            }
            if(empty($v['best_time'])){
                $v['best_time']=time();
            }
            if(empty($v['giving'])){
                $giving=false;
                $FGiving=0;
            }else if($v['giving']==1){
                $giving=true;
                $FGiving=$v['giving'];
            }else{
                $giving=false;
                $FGiving=$v['giving'];
            }
            if(empty($v['goods_price'])){
                $v['goods_price']=0.0;
            }
            $goods[]=[
                "FEntryID" => null,
                "FRowType" => "Standard",
                "FCustMatID" => [
                    "FNumber" => ""
                ],
                "FMaterialID" => [
                    "FNumber" => $v['goods_sn']   //商品货号
                ],
                "FParentMatId" => [
                    "FNumber" => ""
                ],
                "FUnitID" => [
                    "FNumber" => $v['spec_unit'] // 规格
                ],
                "FCurrentInventory" => 0.0,
                "FAwaitQty" => 0.0,
                "FQty" => $v['goods_number'],
                "FTaxPrice"=>$v['goods_price'],
                //"FEntryTaxRate"=>$v['tax_rate'],
                "FAvailableQty" => 0.0,
                "FGiving"=>$FGiving,
                "FDeliveryDate" => date('Y-m-d H:i:s',$v['best_time']),  //最晚送货时间
                "FStockID" => [
                    "FNumber" => $v['StockNubmer'],// 仓库编号
                ],
                "FStockLocID" => [
                    "FSTOCKLOCID__FF100001" => [
                        "FNUMBER" => ""
                    ]
                ],
                "FBACKUPSTOCKID" => [
                    "FNumber" => ""
                ],
                "FBACKUPSTOCKLOCID" =>[
                    "FBACKUPSTOCKLOCID__FF100001" => [
                        "FNUMBER" => ""
                    ],
                ],
                "FMtoNo" => null,
                "FNoteEntry" => null,
                "FBomID" => [
                    "FNumber" => ""
                ],
                "FLot" => [
                    "FNumber" => ""
                ],
                "FPRODUCEDATE" => null,
                "FEXPIRYDATE" => null,
                "FStockStatusId" => [
                    "FNumber" => "KCZT01_SYS"
                ],
                "FOutContROL" => false,
                "FIsFree"=>$giving,
                "FOutMaxQty" => $v['goods_number'],
                "FOutMinQty" => $v['goods_number'],
                "FBaseUnitID"=>[
                    "FNumber"=> "Pcs"
                ],
                "FPriceBaseQty" => $v['goods_number'],
                "FPlanDeliveryDate"=>date('Y-m-d H:i:s',time()),
                "FDeliveryLoc" => [
                    "FNUMBER" => ""
                ],
                "FDeliveryLAddress" => null,
                "FCarryLeadTime" => 0,
                "FJoinCheckQty" => 0.0,
                "FBaseJoinCheckQty" => 0.0,
                "FQualifiedQty" => 0.0,
                "FBaseQualifiedQty" => 0.0,
                "FUnqualifiedQty" => 0.0,
                "FBaseUnqualifiedQty" => 0.0,
                "FJunkedQty" => 0.0,
                "FBaseJunkedQty" => 0.0,
                "FStockUnitID" => [
                    "FNumber" => $v['spec_unit']
                ],
                "FStockQty" => $v['goods_number'],
                "FStockBaseQty" => $v['goods_number'],
                "FOwnerTypeID" => $FOwnerTypeID,
                "FOwnerID" => [
                    "FNumber" => $FOwnerFNumber
                ],
                "FBaseJoinQualifiedQty" => 0.0,
                "FJoinQualifiedQty" => 0.0,
                "FBaseJoinUnqualifiedQty" => 0.0,
                "FJoinUnqualifiedQty" => 0.0,
                "FBaseUQCanSaleQty" => 0.0,
                "FUQCanSaleQty" => 0.0,
                "FJoinDeliChkQty" => 0.0,
                "FBaseJoinDeliChkQty" => 0.0,
                "FJoinDeliChkUQQty" => 0.0,
                "FBaseJoinDeliChkUQQty" => 0.0,
                "FDeliChkTranOutQty" => 0.0,
                "FDeliChkTranOutUQQty" => 0.0,
                "FBaseDeliChkTranOutQty" => 0.0,
                "FSOEntryId" => 0,
                "FBaseDeliChkTranOutUQQty" => 0.0,
                "FOutLmtUnit" => "SAL",
                "FOutLmtUnitID" => [
                    "FNumber" => $v['spec_unit']
                ]
            ];
        }
        return $goods;
    }


    /**
     * 批量提交处理数据
     * */
    public function PostSaveData($arr){
        if(!is_array($arr)){
            return false;
        }
        foreach ($arr as $key=>$val){
            $goods=$this->PostGoodsData($val['GoodsData']);
            if(!$goods){
                continue;
            }
            $data[] = [
                "FID" => "0",
                "FBillTypeID" =>[
                    "FNumber" => "FHTZD01_SYS",
                ],
                "FBillNo" => "",
                "FDate" => date('Y-m-d H:i:s',time()),
                "FSaleOrgId" => [
                    "FNumber" => config('k3cloud.organization'),
                ],
                "FSaleDeptID" =>[
                    "FNumber" => "",
                ],
                "FCustomerID" =>[
                    "FNumber" => config('k3cloud.appcustomer'),
                ],
                "FHeadDeliveryWay" =>[
                    "FNumber" => "",
                ],
                "FHeadLocId" => [
                    "FNUMBER" => ""
                ],
                "FCorrespondOrgId" => [
                    "FNumber" => "",
                ],
                "FCarrierID" => [
                    "FNumber" => "",
                ],
                "FCarriageNO" => $val['order_sn'],
                "FNote" => "",
                "FDeliveryOrgID" => [
                    "FNumber" => config('k3cloud.organization'),
                ],
                "FDeliveryDeptID" => [
                    "FNumber" => ""
                ],
                "FStockerGroupID" =>[
                    "FNumber" => ""
                ],
                "FStockerID" => [
                    "FNumber" => ""
                ],
                "FSaleGroupID" => [
                    "FNumber" => ""
                ],
                "FSalesManID" => [
                    "FNumber" => ""
                ],

                "FReceiverContactID" => [
                    "FName" => ""
                ],
                "FReceiveAddress" => "",
                "FSettleID" => [
                    "FNumber" => config('k3cloud.appcustomer'),
                ],
                "FPayerID" =>[
                    "FNumber" => config('k3cloud.appcustomer'),
                ],
                "FRECEIPTCONDITIONID" => [
                    "FNumber" => ""
                ],
                "FOwnerTypeIdHead" => "BD_OwnerOrg",
                "FOwnerIdHead" => [
                    "FNumber" => ""
                ],
                "SubHeadEntity" => [
                    "FSettleOrgID" => [
                        "FNumber" => config('k3cloud.organization')
                    ],
                    "FSettleCurrID" => [
                        "FNumber" => "PRE001"
                    ],
                    "FSettleTypeID" => [
                        "FNumber" => ""
                    ],
                    "FLocalCurrID" => [
                        "FNumber" => "PRE001"
                    ],
                    "FExchangeTypeID" => [
                        "FNumber" => "HLTX01_SYS"
                    ],
                    "FExchangeRate" => 1.0,
                    "FCreChkDays" => 0,
                    "FCreChkAmount" => 0.0,
                ],
                "FEntity" => [$goods]
            ];
        }
        return $data;
    }

    /**
     * 检查发货通知单单据状态
     * */
    public function CheckConsignmentNoteStatus($FBillNo){
       $FieldKeys='FID,FBillNo,FDocumentStatus,FCLOSESTATUS,FCancelStatus,FCarriageNO';
       $FilterString="FBillNo='".$FBillNo."'";
       return $this->ExecuteBillQuery($FieldKeys,$FilterString);
    }

    /**
     * 检查发货通知单单据状态和作废状态
    */
    public function CheckConsignmentNoteDocumentStatusAndCancelStatus($FBillNo){
        $return =$this->CheckConsignmentNoteStatus($FBillNo);
        if(count($return)>0){
            $FDocumentStatus=$return[0]['FDocumentStatus'];
            $FCancelStatus=$return[0]['FCancelStatus'];
            if(in_array($FDocumentStatus,['A','D','Z']) && $FCancelStatus=='A'){
                return 'A';
            }else{
                return 'B';
            }
        }else{
            return false;
        }
    }


    /**
     *  发货通知单作废
     * */
    public function CancelConsignmentNote($Numbers=[]){
        return $this->ExcuteOperation($Numbers,config('k3cloud.opNumberCancel'));
    }

    /**
    *  根据食得鲜的订单号查询对应的发货单号
     */
    public function GetOrderSnConsignmentNote($FBillNo){
        $FieldKeys='FID,FBillNo,FDocumentStatus,FCreateDate,FDate,FCarriageNO,FCLOSESTATUS,FCancelStatus';
        $FilterString="FBillNo='".$FBillNo."' and FDocumentStatus in('A','D','Z') and FCancelStatus='A'";
        $return=$this->ExecuteBillQuery($FieldKeys,$FilterString);
        if(count($return)){
           return $return;
        }else{
            return false;
        }
    }

    public function GetOrderSnConsignmentNoteList($FBillNo,$FilterWhere=true){
        $FieldKeys='FID,FBillNo,FCarriageNO,FMaterialID.FNumber,FQty,FUnitID.FName,FStockID.FNumber,FDeliveryDate,FOwnerTypeID,FOwnerID.FNumber,FEntity_FEntryID,FIsFree,FGiving,FFreight,FDiscountAmount';
        if($FilterWhere){
            $FilterString="FBillNo='".$FBillNo."' and FDocumentStatus in('A','D','Z') and FCancelStatus='A'";
        }else{
            $FilterString="FBillNo='".$FBillNo."'";
        }
        $return=$this->ExecuteBillQuery($FieldKeys,$FilterString);
        if(count($return)){
            return $return;
        }else{
            return false;
        }
    }

    /**
     * 根据运单号来修改发货通知单-退货退款
     * @param $order_sn
     * @param array $data
    @author echa
     */
    public function UpdateConsignmentNote(array $data){
        if(empty($data['FBillNo'])){
            return false;
        }
        $return=$this->GetOrderSnConsignmentNoteList($data['FBillNo']);
        if(!$return){
            return false;
        }
        $FID=$return[0]['FID'];
        $FBillNo=$return[0]['FBillNo'];
        $order_sn=$return[0]['FCarriageNO'];
        $FFreight=$return[0]['FFreight'];
        $FDiscountAmount=$return[0]['FDiscountAmount'];
        $goodsdata=$data['goods'];
        $goods=array();
        $FOwnerTypeBDOwnerOrg=config('k3cloud.FOwnerTypeBDOwnerOrg');
        foreach ($return as $k=>$v){
            $k3_vmi=0;
            $k3_supplier_sn='';
            $goods_number=$v['FQty'];
            $giving=$v['FGiving'];
            foreach ($goodsdata as $key=>$val){
                if($v['FMaterialID.FNumber']==$val['goods_sn'] && floor($v['FGiving'])==$val['giving']){
                    $giving=$val['giving'];
                    $goods_number=$v['FQty']-$val['op_number'];
                    break;
                }
            }
            if($goods_number<=0){
                continue;
            }
            if($v['FOwnerTypeID']!=$FOwnerTypeBDOwnerOrg){
                $k3_supplier_sn=$v['FOwnerID.FNumber'];
                $k3_vmi=1;
            }
            $goods[]=[
                'goods_sn'=>$v['FMaterialID.FNumber'],
                'spec_unit'=>$v['FUnitID.FName'],
                'goods_number'=>$goods_number,
                'best_time'=>strtotime(str_replace('T',' ',$v['FDeliveryDate'])),
                'StockNubmer'=>$v['FStockID.FNumber'],
                'k3_supplier_sn'=>$k3_supplier_sn,
                'k3_vmi'=>$k3_vmi,
                'giving'=>$giving,
            ];
        }
        if(count($goods)<=0){
            //发货通知单作废
            return $this->CancelConsignmentNote([$data['FBillNo']]);
        }
        $arrdata=[
            'FID'=>$FID,
            'FBillNo'=>$FBillNo,
            'order_sn'=>$order_sn,
            'freight'=>$FFreight,
            'discountamount'=>$FDiscountAmount,
            'GoodsData'=>$goods,
        ];
        return $this->SaveConsignmentNote($arrdata);
    }


    /***
     * 次品退款
     * @param array $data
     * @param DirectTransfersService $directTransfersService
     * @param WarehouseService $warehouseService
    @author echa
     * @return array|bool
     */
    public function UpdateConsignmentNoteAndDirectTransfers(array $data){
        if(empty($data['FBillNo'])){
            return false;
        }
        $return=$this->GetOrderSnConsignmentNoteList($data['FBillNo']);
        if(!$return){
            return false;
        }
        $FID=$return[0]['FID'];
        $FBillNo=$return[0]['FBillNo'];
        $order_sn=$return[0]['FCarriageNO'];
        $FFreight=$return[0]['FFreight'];
        $FDiscountAmount=$return[0]['FDiscountAmount'];
        $goodsdata=$data['goods'];
        $stock_number=$return[0]['FStockID.FNumber'];
//       //根据仓库编号筛选相同分组下面指定仓库类型为次品仓库数据
        $defective_stock=$this->WarehouseService->GetWarehouseTypeInfo($stock_number,'B');
        if(!$defective_stock){
            return false;
        }
        $DestStockNubmer=$defective_stock[0]['FNumber'];//相同分组对应次品仓
        $cngoods=array();//发货通知单商品明细
        $dtgoods=array();//直接调拨商品明细
        $dtgoods_booking=array();
        $FOwnerTypeBDOwnerOrg=config('k3cloud.FOwnerTypeBDOwnerOrg');
        foreach ($return as $k=>$v){
            $k3_vmi=0;
            $k3_supplier_sn='';
            $goods_number=$v['FQty'];
            $giving=$v['FGiving'];
            foreach ($goodsdata as $key=>$val){
                if($v['FMaterialID.FNumber']==$val['goods_sn'] && floor($v['FGiving'])==$val['giving']){
                    $goods_number=$v['FQty']-$val['op_number'];
                    $k3_vmi_out=0;
                    $k3_supplier_sn_out='';
                    if($v['FOwnerTypeID']!=$FOwnerTypeBDOwnerOrg){
                        $k3_supplier_sn=$v['FOwnerID.FNumber'];
                        $k3_vmi=1;
                        $k3_vmi_out=1;
                        $k3_supplier_sn_out=$v['FOwnerID.FNumber'];
                        $dtgoods_booking[]=[
                            'goods_sn'=>$v['FMaterialID.FNumber'],
                            'spec_unit'=>$v['FUnitID.FName'],
                            'goods_number'=>$val['op_number'],
                            'StockNubmer'=>$v['FStockID.FNumber'],
                            'k3_vmi'=>$k3_vmi,
                            'k3_supplier_sn'=>$k3_supplier_sn,
                            'k3_vmi_out'=>$k3_vmi_out,
                            'k3_supplier_sn_out'=>$k3_supplier_sn_out,
                            'DestStockNubmer'=>$DestStockNubmer,
                            'goods_remark'=>'次品退货操作发货通知单:'.$FBillNo.'数据变动',
                        ];
                    }else{
                        $dtgoods[]=[
                            'goods_sn'=>$v['FMaterialID.FNumber'],
                            'spec_unit'=>$v['FUnitID.FName'],
                            'goods_number'=>$val['op_number'],
                            'StockNubmer'=>$v['FStockID.FNumber'],
                            'k3_vmi'=>$k3_vmi,
                            'k3_supplier_sn'=>$k3_supplier_sn,
                            'k3_vmi_out'=>$k3_vmi_out,
                            'k3_supplier_sn_out'=>$k3_supplier_sn_out,
                            'DestStockNubmer'=>$DestStockNubmer,
                            'goods_remark'=>'次品退货操作发货通知单:'.$FBillNo.'数据变动',
                        ];
                    }
                    break;
                }
            }
            if($goods_number<=0){
                continue;
            }
            if($v['FOwnerTypeID']!=$FOwnerTypeBDOwnerOrg){
                $k3_supplier_sn=$v['FOwnerID.FNumber'];
                $k3_vmi=1;
            }
            $cngoods[]=[
                'goods_sn'=>$v['FMaterialID.FNumber'],
                'spec_unit'=>$v['FUnitID.FName'],
                'goods_number'=>$goods_number,
                'best_time'=>strtotime(str_replace('T',' ',$v['FDeliveryDate'])),
                'StockNubmer'=>$v['FStockID.FNumber'],
                'k3_supplier_sn'=>$k3_supplier_sn,
                'k3_vmi'=>$k3_vmi,
                'giving'=>$giving
            ];
        }
        if(count($dtgoods_booking)>0){
            $dtdata_booking=[
                'k3_vmi'=>1,
                'k3_supplier_sn'=>$dtgoods_booking[0]['k3_supplier_sn'],
                'k3_vmi_out'=>1,
                'k3_supplier_sn_out'=>$dtgoods_booking[0]['k3_supplier_sn'],
                'Note'=>$data['note'],
                'GoodsData'=>$dtgoods_booking
            ];
            $this->DirectTransfersService->SaveDirectTransfers($dtdata_booking,true);
        }
        if(count($dtgoods)>0){
            $dtdata=[
                'k3_vmi'=>0,
                'k3_supplier_sn'=>$dtgoods[0]['k3_supplier_sn'],
                'k3_vmi_out'=>0,
                'k3_supplier_sn_out'=>$dtgoods[0]['k3_supplier_sn'],
                'Note'=>$data['note'],
                'GoodsData'=>$dtgoods
            ];
            $this->DirectTransfersService->SaveDirectTransfers($dtdata,true);
        }
        if(count($cngoods)<=0){
            //发货通知单作废
            return $this->CancelConsignmentNote([$data['FBillNo']]);
        }
        $arrdata=[
            'FID'=>$FID,
            'FBillNo'=>$FBillNo,
            'order_sn'=>$order_sn,
            'freight'=>$FFreight,
            'discountamount'=>$FDiscountAmount,
            'GoodsData'=>$cngoods,
        ];
        return $this->SaveConsignmentNote($arrdata);
    }

    /***
     * 缺货退货
     * @param array $data
     * @param MisDeliveryService $misDeliveryService
    @author echa
     * @return array|bool
     */
    public function UpdateConsignmentNoteAndMisDelivery(array $data){
        if(empty($data['FBillNo'])){
            return false;
        }
        $return=$this->GetOrderSnConsignmentNoteList($data['FBillNo']);
        if(!$return){
            return false;
        }
        $FID=$return[0]['FID'];
        $FBillNo=$return[0]['FBillNo'];
        $order_sn=$return[0]['FCarriageNO'];
        $FFreight=$return[0]['FFreight'];
        $FDiscountAmount=$return[0]['FDiscountAmount'];
        $goodsdata=$data['goods'];
        $cngoods=array();
        $mdgoods=array();//需要其他出库的商品
        $mdgoods_booking=array();
        $FOwnerTypeBDOwnerOrg=config('k3cloud.FOwnerTypeBDOwnerOrg');
        foreach ($return as $k=>$v){
            $k3_vmi=0;
            $k3_supplier_sn='';
            $goods_number=$v['FQty'];
            $giving=$v['FGiving'];
            foreach ($goodsdata as $key=>$val){
                if($v['FMaterialID.FNumber']==$val['goods_sn'] && $v['FGiving']==$val['giving']){
                    $goods_number=$v['FQty']-$val['op_number'];
                    if($v['FOwnerTypeID']!=$FOwnerTypeBDOwnerOrg){
                        $k3_supplier_sn=$v['FOwnerID.FNumber'];
                        $k3_vmi=1;
                        $mdgoods_booking[]=[
                            'goods_sn'=>$v['FMaterialID.FNumber'],
                            'spec_unit'=>$v['FUnitID.FName'],
                            'goods_number'=>$val['op_number'],
                            'StockNubmer'=>$v['FStockID.FNumber'],
                            'k3_supplier_sn'=>$k3_supplier_sn,
                            'k3_vmi'=>$k3_vmi,
                        ];
                    }else{
                        $mdgoods[]=[
                            'goods_sn'=>$v['FMaterialID.FNumber'],
                            'spec_unit'=>$v['FUnitID.FName'],
                            'goods_number'=>$val['op_number'],
                            'StockNubmer'=>$v['FStockID.FNumber'],
                            'k3_supplier_sn'=>$k3_supplier_sn,
                            'k3_vmi'=>$k3_vmi,
                        ];
                    }
                    break;
                }
            }
            if($goods_number<=0){
                continue;
            }
            if($v['FOwnerTypeID']!=$FOwnerTypeBDOwnerOrg){
                $k3_supplier_sn=$v['FOwnerID.FNumber'];
                $k3_vmi=1;
            }
            $cngoods[]=[
                'goods_sn'=>$v['FMaterialID.FNumber'],
                'spec_unit'=>$v['FUnitID.FName'],
                'goods_number'=>$goods_number,
                'best_time'=>strtotime(str_replace('T',' ',$v['FDeliveryDate'])),
                'StockNubmer'=>$v['FStockID.FNumber'],
                'k3_supplier_sn'=>$k3_supplier_sn,
                'k3_vmi'=>$k3_vmi,
                'giving'=>$giving
            ];
        }
        if(count($mdgoods_booking)>0){
            $mddata_booking=[
                'k3_vmi'=>1,
                'k3_supplier_sn'=>$mdgoods_booking[0]['k3_supplier_sn'],
                'MD_type'=>5, //其他出库类型(缺货退货)
                'note'=>$data['note'],
                'GoodsData'=>$mdgoods_booking
            ];
            $this->MisDeliveryService->SaveMisDelivery($mddata_booking,true);
        }
        if(count($mdgoods)>0){
            $mddata=[
                'k3_vmi'=>0,
                'k3_supplier_sn'=>$mdgoods[0]['k3_supplier_sn'],
                'MD_type'=>5, //其他出库类型(缺货退货)
                'note'=>$data['note'],
                'GoodsData'=>$mdgoods
            ];
            $this->MisDeliveryService->SaveMisDelivery($mddata,true);
        }
        if(count($cngoods)<=0){
            //发货通知单作废
            return $this->CancelConsignmentNote([$data['FBillNo']]);
        }
        $arrdata=[
            'FID'=>$FID,
            'FBillNo'=>$FBillNo,
            'order_sn'=>$order_sn,
            'freight'=>$FFreight,
            'discountamount'=>$FDiscountAmount,
            'GoodsData'=>$cngoods,
        ];
        return $this->SaveConsignmentNote($arrdata);
    }

    /***
     * 下推销售出库单
     * @param array $Numbers
    @author echa
     * @return array|bool
     */
    public function ConsignmentNotePushSalesRelease($Numbers=[]){
        if(count($Numbers)<=0){
            return false;
        }
        return $this->PushedDown($Numbers,config('k3cloud.ConsignmentNotePushOutStock'),config('k3cloud.SalesRelease'));
    }

    /***
     * 发货通知单并且提交审核并且下推为销售出库单
     * @param array $data
    @author echa
     * @return array|bool
     */
    public function ConsignmentNoteSubmitAndPushSalesRelease($Number)
    {
        if(empty($Number)){
            return false;
        }
        $submitreturn = $this->ConsignmentNoteSubmitAndAudit([$Number]);
        if (empty($submitreturn['Id'])) {
            return false;
        }
        $pushreturn = $this->ConsignmentNotePushSalesRelease([$Number]);
        if (empty($pushreturn['Id'])) {
            return false;
        }
        return $pushreturn;
    }

    /***
     * 提交并审核发货通知单
     * @param array $Number
    @author echa
     * @return bool
     */
    public function ConsignmentNoteSubmitAndAudit($Number=[]){
        if(count($Number)<=0){
            return false;
        }
        $submitreturn=$this->SubmitConsignmentNote($Number);
        if(empty($submitreturn['Id'])){
            return false;
        }
        $auditreturn=$this->AuditConsignmentNote($Number);
        if(empty($auditreturn['Id'])){
            return false;
        }
        return $auditreturn;
    }


    /***
     * 发货通知单操作反审核以及作废单据
     * @param array $Number
    @author echa
     * @return array|bool
     */
    public function UnAuditAndCancelConsignmentNote($Number=[]){
        if(count($Number)<=0){
            return false;
        }
        $return=$this->unAuditConsignmentNote($Number);
        if(empty($return['Id'])){
            return false;
        }
        return $this->CancelConsignmentNote($Number);
    }
}